import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/constants/constant_dict.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_dialog.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_edit.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/lend_or_return.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock_search/udt_tb_docmentstock_search_location_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/utils/utils.dart';

class UdtTbDocmentstockSearchLocationList extends StatefulWidget {
  UdtTbDocmentstockSearchLocationList({Key? key}) : super(key: key);

  @override
  UdtTbDocmentstockSearchLocationState createState() =>
      UdtTbDocmentstockSearchLocationState();
}

class UdtTbDocmentstockSearchLocationState
    extends State<UdtTbDocmentstockSearchLocationList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock();

  String locationcode = "";

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      ///_query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          // CryInput(
          //   width: 250,
          //   label: '档案盒位置编码',
          //   //enable: true,
          //   value: udtTbDocmentstock.locationId,
          //   onSaved: (v) => {udtTbDocmentstock.locationId = v},
          // ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('档案盒编号'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('档案盒名称'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('所属部门'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('档案项目'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('备注'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('存放区域'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('存放位置'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock.fromMap(m);
        return [
          // isDisplayDesktop(context)
          //     ? DataCell(
          //         CryButtonBar(
          //           children: [
          //             CryButton(
          //                 iconData: Icons.edit,
          //                 tip: S.of(context).modify,
          //                 onPressed: () => _edit(udtTbDocmentstock)),
          //           ],
          //         ),
          //       )
          //     : DataCell(Container()),

          DataCell(Text(udtTbDocmentstock.documentno ?? '--')),
          DataCell(Text(udtTbDocmentstock.documentname ?? '--')),
          DataCell(Text(udtTbDocmentstock.departmentName ?? '--')),
          DataCell(Text(udtTbDocmentstock.documenttypeName ?? '--')),
          DataCell(Text(udtTbDocmentstock.remark ?? '--')),

          DataCell(Text(udtTbDocmentstock.areaName ?? '--')),
          DataCell(Text(udtTbDocmentstock.locationName ?? '--')),
        ];
      },
    );
    //_getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        // CryButton(
        //   label: "扫码",
        //   onPressed: () {
        //     //_scan()
        //     _query();
        //   },
        //   iconData: Icons.qr_code_scanner_outlined,
        // )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await DynamicDataApi.getModels(
        model: 'dms.documentlocation', key: 'locationcode', val: locationcode);
    if (responseBodyApi.success!) {
      // page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      this.udtTbDocmentstock.locationId =
          responseBodyApi.data[0]['id'].toString();
      _successloadData();
      //tableKey.currentState!.loadData(page);
    }
  }

  _successloadData() async {
    ResponseBodyApi responseBodyApi = await UdtTbDocmentstockOdooApi.page(
        data: {"page": page, "domainList": udtTbDocmentstock.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
    }
  }

  // _sort(column, {ascending}) {
  //   page.orders[0].column = column;
  //   page.orders[0].asc = ascending ?? !page.orders[0].asc!;
  //   _query();
  // }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbDocmentstockSearchLocationDialog(),
      ),
    ).then((v) {
      if (v != null) {
        locationcode = v;
        _query();
      }
    });
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.qr_code_scanner_outlined),
            title: Text('扫码查询'),
          ),
        ),
      ],
    );
  }
}
